/**
* 报告菜单 报告查询
*/
<template>
  <div style="width: 100%;height: 100%">
    <el-row :model="formInline" style="height: 5%;width: 100%;display: flex;align-items: center;">
      <el-col :span="0.5" style="margin-right: 0.5vw">
        <el-text size="large">搜索:</el-text>
      </el-col>
      <el-col :span="4" style="display: flex;align-items: center;justify-content: center;">
        <el-input size="large" v-model="formInline.userName" placeholder="请输入所属人姓名或手机号"></el-input>
      </el-col>
      <el-col :span="4" style="display: flex;">
        <el-button size="large" style="background-color:#04c1a5;color:#fff" @click="searchByNameOrPhone">
          <font-awesome-icon icon="fas fa-search" />
          <span style="margin-left:1vh">查询</span>
        </el-button>
      </el-col>
      <el-col :span="16">
      </el-col>
    </el-row>
    <!--    查询筛选30%-->
    <el-row style="
    background-color: white;
    height: 35%;
    margin-top: 2vh;
    margin-bottom: 10px;
    border-radius: 10px;
    box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);">
      <filter-list :filter-rows="rows" @updateList="updateList"/>
    </el-row>
    <!-- 分页组件5%-->
    <el-row style="display: flex;justify-content: flex-end;align-items: center;height: 5%;width: 100%;margin-bottom: 10px">
      <el-pagination
          v-model:current-page="pageParam.pageNo"
          v-model:page-size="pageParam.pageSize"
          v-model:total="pageParam.totalCount"
          :page-sizes="[5, 10, 15, 20]"
          :small="false"
          :disabled="false"
          :background="true"
          layout="total, sizes, prev, pager, next, jumper,"
          :total="100"
          :hide-on-single-page="false"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
      />
    </el-row>
    <!--列表-->
    <el-table
        :header-cell-style=" { background: '#F7FBFE' , color: '#000' , 'text-align': 'center' }"
        size="large"
        :cell-style="{'text-align':'center'}"
        style="width: 100%;height: 50%"
        :data="reportList"
        v-loading="loading"
        highlight-current-row
        element-loading-text="拼命加载中">
      <!--      <el-table-column align="center" type="selection" width="60">-->
      <!--      </el-table-column>-->
      <el-table-column sortable prop="reportId" label="报告编号" width="150">
      </el-table-column>
      <el-table-column sortable prop="name" label="患者名称" width="150">
      </el-table-column>
      <el-table-column sortable prop="username" label="患者手机号" width="150">
      </el-table-column>
      <el-table-column sortable prop="age" label="患者年龄" width="150">
      </el-table-column>
      <el-table-column sortable prop="sex" label="患者性别" width="150">
      </el-table-column>
      <el-table-column sortable prop="editDate" label="编辑时间" width="300">
        <template v-slot="scope">
          {{ formatDateTime(scope.row.createdDate) }}
        </template>
      </el-table-column>
      <el-table-column sortable prop="doctorName" label="诊断医师" width="150">
      </el-table-column>
      <el-table-column fixed="right" align="center" label="操作" min-width="200">
        <template v-slot="scope">
          <el-button size="large" style="background-color:#edf7f6;color:#4CAF50;"  @click="showReport(scope.row.reportId)">
            <font-awesome-icon icon="fas fa-check-circle" />
            <span style="margin-left:1vh">查看</span>
          </el-button>
          <el-button size="large" style="background-color:#edf7f6;color:#4CAF50;"  @click="showDownloadDialog(scope.row.reportId)">
            <font-awesome-icon icon="fas fa-download" />
            <span style="margin-left:1vh">下载</span>
          </el-button>


        </template>
      </el-table-column>
    </el-table>
    <!--报告弹窗-->
    <el-dialog v-model="reportVisible"
               title="睡眠呼吸检测报告"
               align-center
               center
               :style="{ 'height': '100%', 'width': '50vw' }"
               @close="reportClose"
    >
      <el-breadcrumb :separator-icon="ArrowRight" class="breadcrumb">
        <el-breadcrumb-item v-for="(item, index) in breadcrumbItems" :key="index" @click="handlePageChange(index + 1)">
          <el-text :class="{ 'active': currentPage === index + 1 }" size="large">{{ item }}</el-text>
        </el-breadcrumb-item>
        <el-breadcrumb-item>
          <el-text :class="{ 'active': currentPage === 9 }" size="large"></el-text>
        </el-breadcrumb-item>
      </el-breadcrumb>
      <el-container style="display: flex;align-items: center;justify-content: center;flex-direction: column; height: 100%;">
        <!--个人信息-->
        <user-info-card v-if="currentPage === 1" :currentReportId="currentReportId" />
        <!-- 呼吸 -->
        <breath-card v-if="currentPage === 2" style="height: 80vh" :currentReportId="currentReportId" :enable-edit="enableEdit"/>
        <!--鼾声-->
        <snore-card v-if="currentPage === 3" style="height: 80vh" :currentReportId="currentReportId" :enable-edit="enableEdit"/>
        <!--睡眠状态-->
        <sleep-status-card v-if="currentPage === 4" style="height: 80vh" :currentReportId="currentReportId" :enable-edit="enableEdit"/>
        <!--心率-->
        <heart-rate-card v-if="currentPage === 5" style="height: 80vh" :currentReportId="currentReportId" :enable-edit="enableEdit"/>
        <!--心律  -->
        <HeartRhythmCard v-if="currentPage === 6" style="height: 80vh" :currentReportId="currentReportId" :enable-edit="enableEdit"/>
        <!-- 体位 -->
        <body-card v-if="currentPage === 7" style="height: 80vh" :currentReportId="currentReportId" :enable-edit="enableEdit"/>
        <!--综合评价-->
        <DiagnosisRecord v-if="currentPage === 8" style="height: 80vh" :currentReportId="currentReportId" :enable-edit="enableEdit"/>

      </el-container>
      <!--    翻页按钮-->
      <div v-if="reportVisible" class="floating-buttons">
        <el-text style="color: white;font-weight: 700;" size="large" >上一项</el-text>
        <div style="display: flex;
        align-items: center;
        justify-content: center;
        margin-bottom: 5vh">
          <el-button @click="prev" class="paging_button" :type="'text'">
            <el-icon class="paging_button_icon">
              <ArrowUp />
            </el-icon>
          </el-button >
        </div>
        <div style="display: flex;align-items: center;justify-content: center">
          <el-button @click="next" class="paging_button" :type="'text'">
            <el-icon class="paging_button_icon">
              <ArrowDown />
            </el-icon>
          </el-button>
        </div>
        <el-text style="color: white;font-weight: 700;" size="large">下一项</el-text>
      </div>
    </el-dialog>

    <!--  下载报告内容  -->
    <el-dialog v-model="downloadReportVisible"

               title="睡眠呼吸检测报告"
               align-center
               center
               :style="{ 'height': '100%', 'width': '50vw' ,'background-color': 'white', 'overflow': 'auto'}"
               @close="reportClose"
    >
      <div class="reportToPdf"  id="reportId" >
        <el-button class="output" @click="printReport">导出此报告</el-button>
        <div class="reportPdfPage">
          <!--个人信息-->
          <user-info-card  :currentReportId="currentReportId" />
        </div>

        <div class="reportPdfPage">
          <!-- 呼吸 -->
          <breath-card v-if="downloadReportVisible" style="height: 80vh;margin-top: 50px" :currentReportId="currentReportId" :enable-edit="enableEdit"/>
        </div>

        <div class="reportPdfPage">
          <!--鼾声-->
          <snore-card  style="height: 80vh;margin-top: 50px" :currentReportId="currentReportId" :enable-edit="enableEdit"/>
        </div>

        <div class="reportPdfPage">
          <!--睡眠状态-->
          <sleep-status-card  style="height: 80vh ;margin-top: 50px" :currentReportId="currentReportId" :enable-edit="enableEdit"/>
        </div>

        <div class="reportPdfPage">
          <!--心率-->
          <heart-rate-card v-if="downloadReportVisible"  style="height: 80vh;margin-top: 60px" :currentReportId="currentReportId" :enable-edit="enableEdit"/>
        </div>

        <div class="reportPdfPage">
          <!--心律-->
          <HeartRhythmCard  style="height: 80vh;margin-top: 60px" :currentReportId="currentReportId" :enable-edit="enableEdit"/>
        </div>

        <div class="reportPdfPage">
          <!-- 体位 -->
          <body-card  style="height: 80vh;margin-top: 50px" :currentReportId="currentReportId" :enable-edit="enableEdit"/>
        </div>

        <div class="reportPdfPage">
          <!--综合评价-->
          <DiagnosisRecord  style="height: 80vh;margin-top: 50px" :currentReportId="currentReportId" :enable-edit="enableEdit"/>
        </div>


      </div>

    </el-dialog>




  </div>
</template>

<script setup>
import {FontAwesomeIcon} from "@fortawesome/vue-fontawesome";
import {onMounted, ref} from 'vue';
import doctor from "@/api/doctor.js";
import {
  ArrowUp,
  ArrowDown,
  ArrowRight
} from '@element-plus/icons-vue'
import report from "@/api/report.js";
import {ElMessage} from "element-plus";
import UserInfoCard from "@/components/cards/userInfoCard.vue";
import SleepStatusCard from "@/components/cards/sleepStatusCard.vue";
import HeartRateCard from "@/components/cards/heartRateCard.vue";
import SnoreCard from "@/components/cards/snoreCard.vue";
import BreathCard from "@/components/cards/breathCard.vue";
import BodyCard from "@/components/cards/bodyCard.vue";
import DiagnosisRecord from "@/components/cards/diagnosisRecord.vue";
import HeartRhythmCard from "@/components/cards/heartRhythmCard.vue";
import {useAuthStore} from "@/stores/auth.js";
import FilterList from "@/components/tableViews/filterList.vue";
import htmlToPdf from "@/utils/htmlToPDF";

const authStore = useAuthStore();
const loading = ref(false);
const formInline = ref({
  userName: '',
});
const enableEdit = ref(false)
const breadcrumbItems = ["个人信息", "呼吸", "鼾声", "睡眠状态", "心率与血氧","心律", "体位", "记录"];


//报告编辑与查看
const reportVisible = ref(false);
const currentReportId = ref()
const currentPage = ref(1);
const showReport = (reportId)=>{
  reportVisible.value = true;
  currentReportId.value = reportId
}
const handlePageChange = (newPage) => {
  currentPage.value = newPage;
};
const prev = () =>{
  if (currentPage.value > 1){
    currentPage.value--;
  }
}
const next = () =>{
  if (currentPage.value < 8){
    currentPage.value++;
  }
}
const reportClose = ()=>{
  currentPage.value = 1
}

// 下载报告弹窗
const downloadReportVisible= ref(false);
const showDownloadDialog= (reportId)=>{
  downloadReportVisible.value = true;
  currentReportId.value = reportId
}

//生成并下载报告pdf
const printReport = async () => {
  // await loadOxygenData(currentReportId.value); // 等待数据加载完成
  htmlToPdf.getPdfPage('睡眠呼吸监测报告', 'reportPdfPage');
};
// const printReport = () => {
//
//   htmlToPdf.getPdfPage('睡眠呼吸监测报告', 'reportPdfPage')
// };

//查询关键字编辑
const rows = ref([
  // { label: '医嘱关键词', buttons: [
  //     { text: '-全部-', selected: true },
  //     { text: '阻塞性睡眠呼吸暂停', selected: false },
  //     { text: '中央性睡眠呼吸暂停', selected: false },
  //     { text: 'SDB严重程度', selected: false },
  //     { text: '气道阻塞', selected: false },
  //     { text: '气道阻塞', selected: false },
  //     { text: 'AHI', selected: false },
  //     { text: 'CPAP治疗建议', selected: false },
  //     { text: '失眠', selected: false },
  //     { text: '睡眠时期延迟综合症', selected: false },
  //     { text: '睡眠时期提前综合症', selected: false },
  //     { text: '常规睡眠时间', selected: false },
  //     { text: '短时睡眠综合症', selected: false },
  //     { text: '心房颤动', selected: false },
  //     { text: '心律失常', selected: false },
  //     { text: '心衰', selected: false },
  //     { text: '阻塞性睡眠呼吸暂停', selected: false },
  //     { text: '鼾声评估', selected: false },
  //     { text: '体位性睡眠呼吸暂停', selected: false },
  //
  //   ] },
  { label: '状态',
    enableEdit: false,
    buttons: [
      { text: '-已审核-',value: 1, selected: true },
    ] },
  { label: '性别',  enableEdit: false,buttons: [
      { text: '-全部-',value:null, selected: true },
      { text: '男',value:'男', selected: false },
      { text: '女',value:'女', selected: false },
    ] },
  { label: '年龄',  enableEdit: false,buttons: [
      { text: '-全部-',value:null, selected: true },
      { text: '0到10岁',value:0, selected: false },
      { text: '11到20岁',value:10, selected: false },
      { text: '21到30岁',value:20, selected: false },
      { text: '31到40岁',value:30, selected: false },
      { text: '51到50岁',value:40, selected: false },
      { text: '51到60岁',value:50, selected: false },
      { text: '60岁以上',value:200, selected: false },
    ] },
  { label: '生成时间',  enableEdit: false,buttons: [
      { text: '-全部-', value: null,selected: true },
      { text: '刚刚',value: 1, selected: false },
      { text: '最近1天', value: 2,selected: false },
      { text: '最近7天', value: 7,selected: false },
      { text: '最近两周', value: 14,selected: false },
      { text: '最近1个月', value: 30,selected: false },
      { text: '最近3个月', value: 90,selected: false },
      { text: '最近一年', value: 365,selected: false },
      { text: '一年以上', value: null,selected: false },
    ] },
  { label: '最近编辑',
    enableEdit: false,
    buttons: [
      { text: '-全部-', value:null, selected: true },
      { text: '刚刚', value:1,selected: false },
      { text: '最近1天', value:2,selected: false },
      { text: '最近7天', value:7,selected: false },
      { text: '最近两周', value:14,selected: false },
      { text: '最近1个月', value:30,selected: false },
      { text: '最近3个月',value:90, selected: false },
      { text: '最近一年', value:365,selected: false },
      { text: '一年以上',value:null, selected: false },
    ] },
]);
const updateList = (newRows) =>{
  const finishReportQuery = {
    pageIndex: pageParam.value.pageNo - 1,
    pageSize: pageParam.value.pageSize
  }
  //调用更新方法
  updateFinishReportQuery(newRows, finishReportQuery);
  //执行查询
  requestReportList(finishReportQuery);
}

//分页组件
const pageParam = ref({
  pageNo:1,
  pageSize:10,
  totalCount:10,
  totalPages:10,
  nextPage:0,
  prePage:0,
  hasPre:false,
  hasNext:true,
});
const handleCurrentChange = (newPage)=>{
  pageParam.value.pageNo = newPage;
  const finishReportQuery = {
    status: null,
    sex: null,
    minYear: null,
    maxYear: null,
    minCreatedDate: null,
    maxCreatedDate: null,
    minEditDate: null,
    maxEditDate: null,
    pageIndex: pageParam.value.pageNo - 1,
    pageSize: pageParam.value.pageSize
  }
  // 调用更新方法
  updateFinishReportQuery(rows.value, finishReportQuery);
  //执行查询
  requestReportList(finishReportQuery);
}
const handleSizeChange = ()=>{
  const finishReportQuery = {
    pageIndex: pageParam.value.pageNo - 1,
    pageSize: pageParam.value.pageSize
  }
  //调用更新方法
  updateFinishReportQuery(rows.value, finishReportQuery);
  //执行查询
  requestReportList(finishReportQuery);
}

//报告查询
const reportList = ref([]);
const role = ref('')
onMounted(() => {
  role.value = authStore.role;
  getReportList()
});
const updateFinishReportQuery = (rows,finishReportQuery)=>{
  finishReportQuery.status = updateSelectedValue(rows[0].buttons);
  finishReportQuery.sex = updateSelectedValue(rows[1].buttons);
  finishReportQuery.minYear = updateSelectedValue(rows[2].buttons);
  finishReportQuery.maxYear = updateSelectedValue(rows[2].buttons) + 10;
  finishReportQuery.minCreatedDate = updateTime(rows[3].buttons, finishReportQuery.currentTime);
  finishReportQuery.maxCreatedDate = getCurrentDate();
  finishReportQuery.minEditDate = updateTime(rows[4].buttons, finishReportQuery.currentTime);
  finishReportQuery.maxEditDate = getCurrentDate();
  if (finishReportQuery.minYear===null || finishReportQuery.maxYear===null){
    finishReportQuery.minYear = null;
    finishReportQuery.maxYear = null;
  }
  if (finishReportQuery.minCreatedDate===null || finishReportQuery.maxCreatedDate===null){
    finishReportQuery.minCreatedDate = null;
    finishReportQuery.maxCreatedDate = null;
  }
  if (finishReportQuery.minEditDate===null || finishReportQuery.maxEditDate===null){
    finishReportQuery.minEditDate = null;
    finishReportQuery.maxEditDate = null;
  }
  const userInfo = formInline.value.userName
  if (userInfo !== ''){
    if (userInfo.length === 11){
      finishReportQuery.userName = formInline.value.userName
    }else{
      finishReportQuery.name = formInline.value.userName
    }
  }
}
function updateSelectedValue(buttons) {
  for (const button of buttons) {
    if (button.selected) {
      return button.value;
    }
  }
  return null;
}
function getCurrentDate() {
  const now = new Date();
  const year = now.getFullYear();
  const month = String(now.getMonth() + 1).padStart(2, '0');
  const day = String(now.getDate()).padStart(2, '0');
  return `${year}-${month}-${day}`;
}
function updateTime(buttons, currentDate) {
  for (const button of buttons) {
    if (button.selected) {
      if (button.value === null) {
        return null;
      } else {
        const time = new Date();
        time.setDate(time.getDate() - button.value);
        const year = time.getFullYear();
        const month = String(time.getMonth() + 1).padStart(2, '0');
        const day = String(time.getDate()).padStart(2, '0');
        return `${year}-${month}-${day}`;
      }
    }
  }
  return currentDate; // 默认取当前时间
}
const getReportList = ()=>{
  const finishReportQuery = {
    status: updateSelectedValue(rows.value[0].buttons),
    pageIndex: pageParam.value.pageNo - 1,
    pageSize: pageParam.value.pageSize
  }
  requestReportList(finishReportQuery)
}
const requestReportList = (finishReportQuery) =>{
  loading.value = true
  if (role.value === 'doctor'){
    finishReportQuery.doctorId = authStore.userId;
  }
  doctor.searchFinishReportList(finishReportQuery)
      .then((res) => {
        if (res.data.code === 200) {
          reportList.value = res.data.data.result
        }
        updatePageParams(res.data.data);
      })
      .catch((err) => {
        console.log(err);
      })
      .finally(()=>{
        loading.value = false
      });
}
function updatePageParams(pageData) {
  pageParam.value.pageNo = pageData.pageNo;
  pageParam.value.pageSize = pageData.pageSize;
  pageParam.value.totalCount = pageData.totalCount;
  pageParam.value.totalPages = pageData.totalPages;
  pageParam.value.nextPage = pageData.nextPage;
  pageParam.value.hasNext = pageData.hasNext;
  pageParam.value.prePage = pageData.prePage;
  pageParam.value.hasPre = pageData.hasPre;
}
function formatDateTime(dateTimeString) {
  const date = new Date(dateTimeString);
  const year = date.getFullYear();
  const month = String(date.getMonth() + 1).padStart(2, '0');
  const day = String(date.getDate()).padStart(2, '0');
  const hour = String(date.getHours()).padStart(2, '0');
  const minute = String(date.getMinutes()).padStart(2, '0');
  const second = String(date.getSeconds()).padStart(2, '0');
  return `${year}-${month}-${day} ${hour}:${minute}:${second}`;
}

//信息查询
const searchByNameOrPhone = ()=>{
  let finishReportQuery = {
    status: 1,
    pageIndex: pageParam.value.pageNo - 1,
    pageSize: pageParam.value.pageSize,
  }
  if (formInline.value.userName.length === 11){
    finishReportQuery.userName = formInline.value.userName
  }else{
    finishReportQuery.name = formInline.value.userName
  }
  requestReportList(finishReportQuery)
}
</script>

<style scoped lang="scss">
.breadcrumb {
  margin-left: 5%;
  margin-bottom: 2vh;
  font-size: 1.5vh;
  font-weight: 600;
  cursor: pointer;
}
::v-deep .customer-table th{
  border:none;
}
::v-deep .customer-table td,.customer-table th.is-leaf {
  border:none;
}
::v-deep .el-pagination.is-background .el-pager li:not(.disabled).active {
  background-color: green;
  color: #fff;
}
::v-deep .el-pagination.is-background .el-pager li:not(.disabled):hover {
  background-color: #00CAC9;
  color: #fff; /* 鼠标悬浮时的文字颜色为白色 */
}
::v-deep .el-pagination.is-background .el-pager li:not(.disabled) {
  background-color: #00CAC9;
}
::v-deep .el-pagination__sizes .el-select-dropdown__item {
  color: red; /* 修改这里为你想要的颜色 */
}

::v-deep .el-pagination__sizes .el-select-dropdown__item.selected {
  color: blue; /* 修改被选中项的颜色 */
}

::v-deep .el-pagination .el-select .el-select-dropdown__item:hover {
  color: green; /* 修改鼠标悬停项的颜色 */
}

.select_bottom {

  .el-select-dropdown__item.selected {
    color: red;
  }

  .el-select-dropdown__item.hover,
  .el-select-dropdown__item:hover {
    background: red;
    color: #fff;
  }
}
.active{
  color: #04c1a5;
}
.floating-buttons {
  position: fixed;
  top: 50%;
  right: 20%;
  transform: translateY(-50%);
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  /* background-color: white; */
  padding: 10px;
  width: 4vw;
}
.paging_button{
  display: flex;
  align-items: center;
  justify-content: center;

}
.paging_button_icon{
  display: flex;
  align-items: center;
  justify-content: center;
  flex-direction: column;
  font-size: 4.5vw;
  color: #04c1a5;
}
.reportToPdf {
  width: 100%;
  height: 100%;


  .reportPdfPage{
    width: 100%;
    height: 100%;
    display: flex;
    justify-content: center;
    flex-direction: column;
    align-items: center;
    //height: 100%;
  }
}

.output {
  top: 18px;
  left: 70px;
  width: 100px;
  height: 40px;
  background-color: #2177b8;
  position: absolute;
  border-radius: 10px;
  color: #fff;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;

}

</style>